package com.filldream.fastboot.core.manager;

import cn.hutool.core.date.DateUtil;
import com.filldream.fastboot.base.mapper.ClsNewsMapper;
import com.filldream.fastboot.common.entity.B;
import com.filldream.fastboot.common.entity.R;
import com.filldream.fastboot.common.okutil.RobotUtil;
import com.filldream.fastboot.common.okutil.cls.ClsUtil;
import com.filldream.fastboot.common.okutil.cls.dto.ClsAnchorDTO;
import com.filldream.fastboot.common.okutil.cls.dto.ClsNewsSimpleItem;
import com.filldream.fastboot.common.util.JsonUtil;
import com.filldream.fastboot.common.util.WsUtil;
import com.filldream.fastboot.core.cache.CacheMap;
import com.filldream.fastboot.core.cache.CacheObj;
import com.filldream.fastboot.core.cache.CacheUtil;
import com.filldream.fastboot.core.service.websocket.ClsNewsServer;
import com.filldream.fastboot.core.thread.ThreadPoolUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class ClsNewsManager {

    @Resource
    private ClsNewsMapper clsNewsMapper;

    /**
     * 获取财联社头条新闻
     * 及时获取，将没有的新闻记录在表
     * @return
     */
    public R<List<ClsNewsSimpleItem>> refreshClsNews() {
        List<ClsNewsSimpleItem> clsNewsList = ClsUtil.getClsNewsList();
        List<ClsNewsSimpleItem> waitAddList = new LinkedList<>();
        if( ObjectUtils.isNotEmpty( clsNewsList ) ){
            //查询已有的数据
            List<String> codes = clsNewsMapper.getAllId(1);
            for (ClsNewsSimpleItem clsNews : clsNewsList) {
                boolean hasFlag = codes.stream().anyMatch(t -> t.equals(clsNews.getId()));
                if( !hasFlag && clsNewsMapper.hasRepeatTitle(clsNews.getTitle(),1) <=0 ){
                    int insert = clsNewsMapper.insert(clsNews);
                    if(insert > 0){
                        waitAddList.add(clsNews);
                    }
                }
            }
        }
        //推送消息到ws
        ThreadPoolUtil.R.getExecutor().execute(() -> {
            Boolean sendResult = new ClsNewsServer().sendNewsList(waitAddList);
            if( sendResult ){
                clsNewsMapper.modifyWsNews( waitAddList.stream().map(ClsNewsSimpleItem::getDbId).collect(Collectors.toList()) );
            }
        });
        return R.autoSuccess(waitAddList);
    }

    /**
     * 自动发送消息给机器人
     * @return
     */
    public B autoSendOwner(List<String> senOwnerList,Integer sourceType,Boolean forceFlag){
        List<ClsNewsSimpleItem> zrWaitList = new ArrayList<>();
        List<ClsNewsSimpleItem> sunWaitList = new ArrayList<>();
        List<ClsNewsSimpleItem> addList = clsNewsMapper.getNotSendOwnerList(senOwnerList,sourceType);
        for (ClsNewsSimpleItem news : addList) {
            List<String> sendOwnerList = news.getSendOwnerList();
            if( !sendOwnerList.contains("zr") ){
                zrWaitList.add(news.toClsNewsSimpleItem());
                sendOwnerList.add("zr");
            }
            if( !sendOwnerList.contains("sun") && (!RobotUtil.isSleepTime() || forceFlag) ){
                sunWaitList.add(news.toClsNewsSimpleItem());
                sendOwnerList.add("sun");
            }
            news.setSendOwner(JsonUtil.toJson(sendOwnerList));
            clsNewsMapper.updateById(news);
        }
        //发消息
        ThreadPoolUtil.J.getExecutor().execute( () ->{
            Map<String, String> btnMap = new HashMap<>();
            String refreshUrl = "https://www.cls.cn/depth?id=1000";
            btnMap.put("来源:财联社", refreshUrl);
            RobotUtil.autoDD( sunWaitList, btnMap );
            RobotUtil.autoFs( zrWaitList );
        });
        return B.success();
    }

    /**
     * 补充发送ws消息
     * @return
     */
    public R<List<ClsNewsSimpleItem>> sendWs(){
        AtomicReference<Boolean> hasSendOkFlag = new AtomicReference<>(false);
        List<ClsNewsSimpleItem> waitSendList = clsNewsMapper.getWaitWsNews();
        if(ObjectUtils.isNotEmpty(waitSendList)){
            Map<String, Session> sessionMap = new ClsNewsServer().getSessionMap();
            if( !sessionMap.isEmpty() ){
                sessionMap.forEach((sessionId,session)->{
                    Integer sendResult = WsUtil.sendText(session, JsonUtil.toJson(R.successd(waitSendList)));
                    //只要成功发送了一个人，那都是发送了，其他人收不到就算了
                    if( sendResult.equals(1) && !hasSendOkFlag.get()){
                        hasSendOkFlag.set(true);
                        clsNewsMapper.modifyWsNews( waitSendList.stream().map(ClsNewsSimpleItem::getDbId).collect(Collectors.toList()) );
                    }
                });
            }
        }
        return R.successd( waitSendList );
    }

    public void refreshClsAnchor() {
        String dateStr = DateUtil.formatDate(new Date());
        List<ClsAnchorDTO> sendList = new ArrayList<>();
        List<ClsAnchorDTO> clsAnchorList = ClsUtil.getClsAnchor(dateStr);
        if( ObjectUtils.isNotEmpty(clsAnchorList) ){
            //获取历史缓存
            CacheObj<List<ClsAnchorDTO>> cacheObj = CacheUtil.getCacheList(CacheMap.CLS_ANCHOR, ClsAnchorDTO.class, dateStr);
            if( ObjectUtils.isNotEmpty(cacheObj.getData()) ){
                List<ClsAnchorDTO> cacheList = cacheObj.getData();
                //按照ClsAnchorDTO的key字段查出在cacheList中没有的clsAnchorList中的元素
                for (ClsAnchorDTO clsAnchor : clsAnchorList) {
                    boolean hasFlag = cacheList.stream().anyMatch(t -> t.getKey().equals(clsAnchor.getKey()));
                    if( !hasFlag ){
                        sendList.add(clsAnchor);
                    }
                }
            }else{
                sendList = clsAnchorList;
            }
            CacheUtil.cacheObj( cacheObj.getCacheKey(), clsAnchorList , 28800);
        }

        //组装发送内容
        final List<ClsAnchorDTO> sendListTemp = sendList;
        ThreadPoolUtil.J.getExecutor().execute( () ->{
            List< ClsNewsSimpleItem > list = new ArrayList<>();
            for (ClsAnchorDTO item : sendListTemp) {
                list.add( item.toClsNewsSimpleItem() );
            }
            RobotUtil.autoDD( list );
        });

    }
}
